#!/bin/bash
#
# Copyright (C) 2015 Baidu.com, Inc. All Rights Reserverd
# Author: zhousongsong
# Date: 2015/11/12
# Brief:
#   install and deploy broc

#set -x
set -e
set -u
declare -r PROTOBUF=$HOME/protobuf
declare -r PROTOC=$PROTOBUF/bin/protoc

# print help information
function help() 
{
    echo "Usage: sh install [protobuf|proto]"
    echo "Options:"
    echo "    protobuf : install protobuf in $HOME/protobuf"
    echo "    proto    : compile broc's proto files"
}

function err() 
{
    echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2
}

function deploy_protobuf() 
{
    # to install protobuf
    if [[ ! -e $PROTOC ]]; then
        echo "-- installing protobuf ..."
        tar -xzvf ./protobuf-2.6.1.tar.gz
        [[ $? -ne 0 ]] && err "-- unpack ./protobuf-2.6.1.tar.gz failed" && return 1
        (cd protobuf-2.6.1 && ./configure --prefix=$PROTOBUF && make -j12 && make install)
        [[ $? -ne 0 ]] && err "-- compile protobuf failed" && return 1
        (cd protobuf-2.6.1/python && python setup.py build && python setup.py install)
        [[ $? -ne 0 ]] && err "-- install protobuf failed" && return 1
        echo "-- installing protobuf success"
        rm -rf protobuf-2.6.1
    else
        echo "-- protobuf has been installed"
    fi
    return 0
}

function deploy_proto() 
{
    # compile proto file
    echo "-- compile broc proto files ..."
    $PROTOC -I=../proto --python_out=../dependency ../proto/*.proto
    [[ $? -ne 0 ]] && err "-- compile broc proto files failed" && return 1
    echo "-- compile broc proto files success" && return 0
}

function main() 
{
    [[ $# -lt 1 ]] && help && return 1
    case "$1" in
            protobuf)
                    deploy_protobuf
                    ;;     
            proto)
                    deploy_proto
                    ;;     
                 *)
                    help
                    ;;
    esac
}

main $@
